define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'vue'], function ($, undefined, Backend, Table, Form, Vue) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'mental/test_main/index' + location.search,
                    add_url: 'mental/test_main/add',
                    edit_url: 'mental/test_main/edit',
                    del_url: 'mental/test_main/del',
                    multi_url: 'mental/test_main/multi',
                    table: 'mental_testmain',
                },

            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [{
                        checkbox: true
                    },
                    {
                        field: 'id',
                        title: __('Id')
                    },
                    {
                        field: 'type',
                        title: __('Type'),
                        searchList: {
                            "skip": __('Type skip'),
                            "mark": __('Type mark'),
                            "component": __('Type component')
                        },
                        formatter: Table.api.formatter.normal
                    },
                    {
                        field: 'name',
                        title: __('Category_id')
                    },
                    {
                        field: 'title',
                        title: __('Title')
                    },
                    {
                        field: 'price',
                        title: __('Price'),
                        operate: 'BETWEEN'
                    },
                    {
                        field: 'pay_mode',
                        title: __('Pay_mode'),
                        searchList: {
                            "0": "免费",
                            "1": "付费查看",
                            "2": "付费测试"
                        },
                        formatter: Table.api.formatter.normal
                    },
                    {
                        field: 'switch',
                        title: __('Switch'),
                        searchList: {
                            "1": __('Yes'),
                            "0": __('No')
                        },
                        table: table,
                        formatter: Table.api.formatter.toggle
                    },
                    // {
                    //     field: 'recommendIs',
                    //     title: __('recommendIs'),
                    //     searchList: {
                    //         "1": __('Yes'),
                    //         "0": __('No')
                    //     },
                    //     table: table,
                    //     formatter: Table.api.formatter.toggle
                    // },
                    {
                        field: 'image',
                        title: __('Image'),
                        events: Table.api.events.image,
                        formatter: Table.api.formatter.image
                    },
                    {
                        field: 'createtime',
                        title: __('Createtime'),
                        operate: 'RANGE',
                        addclass: 'datetimerange',
                        formatter: Table.api.formatter.datetime
                    },
                    {
                        field: 'updatetime',
                        title: __('Updatetime'),
                        operate: 'RANGE',
                        addclass: 'datetimerange',
                        formatter: Table.api.formatter.datetime
                    },
                    {
                        field: 'operate',
                        title: __('Operate'),
                        table: table,
                        events: Table.api.events.operate,
                        formatter: Table.api.formatter.operate,
                        buttons: [
                            {
                                name: 'dimension',
                                title: '维度',
                                text: '维度',
                                // extend: `data-area='["1100px","600px"]'`,
                                classname: 'btn btn-xs btn-primary btn-dialog',
                                icon: 'fa',
                                url: 'mental/test_main/edit_dimension',
                                hidden: function (row) {

                                    return false;
                                }
                            },

                            {
                                name: 'ruleConfig',
                                title: '规则设置',
                                text: '规则设置',
                                classname: 'btn btn-xs btn-primary btn-dialog',
                                icon: 'fa',
                                url: 'mental/test_main/ruleConfig',
                                hidden: function (row) {
                                    if (row.dimensionRule == 4) {
                                        return false;
                                    }
                                    return true;
                                }
                            },

                            {
                                name: 'question',
                                title: '题库管理',
                                text: '题库管理',
                                extend: `data-area='["1100px","600px"]'`,
                                classname: 'btn btn-xs btn-primary btn-dialog',
                                icon: 'fa',
                                url: 'mental/question/index',
                                hidden: function (row) {

                                    return false;
                                }
                            },
                            {
                                name: 'edit_result',
                                title: __('题库展示'),
                                text: __('题库展示'),
                                extend: `data-area='["1100px","600px"]'`,
                                classname: 'btn btn-xs btn-primary btn-dialog',
                                icon: 'fa',
                                url: 'mental/test_main/edit_result',
                                hidden: function (row) {
                                    if (row.type == 'component') {
                                        return true;
                                    }
                                    return false;
                                }
                            },
                            {
                                name: 'report',
                                title: '报告管理',
                                text: '报告管理',
                                extend: `data-area='["1100px","600px"]'`,
                                classname: 'btn btn-xs btn-primary btn-dialog',
                                icon: 'fa',
                                url: 'mental/testreport/index',
                                hidden: function (row) {

                                    return false;
                                }
                            },

                            {
                                name: 'edit_result',
                                title: __('Edit result'),
                                text: __('Edit result'),
                                extend: `data-area='["1100px","600px"]'`,
                                classname: 'btn btn-xs btn-primary btn-dialog',
                                icon: 'fa fa-pencil',
                                url: 'mental/test_main/component',
                                hidden: function (row) {
                                    if (row.type != 'component') {
                                        return true;
                                    }
                                    return false;
                                }
                            },

                        ]
                    }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);



            // 启动和暂停按钮
            $(document).on("click", ".btn-copy", function () {
                //在table外不可以使用添加.btn-change的方法
                //只能自己调用Table.api.multi实现
                //如果操作全部则ids可以置为空
                var ids = Table.api.selectedids(table);
                Table.api.multi("changestatus", ids.join(","), table, this);
            });


        },
        edit_result: function () {
            Table.api.init();
            this.table.question();
            let question_ids = $("#question_ids").val();
            this.table.data = JSON.parse(question_ids);
            let that = this;

            console.log(Fast)
            //移除控制
            $("#question").on("click", ".btn-remove", function () {
                let question_id = $(this).data('question');
                $(this).closest(".json_list").remove();
                let index = that.table.data.indexOf(question_id);
                that.table.data.splice(index, 1);
            });

            setTimeout(() => {
                //拖拽排序
                $("#question").dragsort({
                    itemSelector: 'div',
                    dragSelector: ".btn-dragsort",
                    dragEnd: function () {
                        console.log(77777)
                    },
                    placeHolderTemplate: "<div></div>"
                });
            }, 5000)

            Controller.api.bindevent();
        },
        table: {
            data: [],
            question: function () {
                // 表格1
                var table = $("#table");
                table.bootstrapTable({
                    url: 'mental/question/index',
                    toolbar: '#toolbar',
                    sortName: 'id',
                    sortOrder: 'asc',
                    search: false,
                    searchFormTemplate: 'customformtpl',
                    queryParams: function (params) {
                        var filter = JSON.parse(params.filter);
                        var op = JSON.parse(params.op);
                        var main_id = Fast.api.query('ids');

                        if (main_id) {
                            filter.main_id = main_id;
                            op.main_id = '=';
                            params.filter = JSON.stringify(filter);
                            params.op = JSON.stringify(op);
                            //   funcUrlDel('ids');
                        }
                        return params;
                    },
                    columns: [
                        [{
                            field: 'state',
                            checkbox: true,
                        },
                        {
                            field: 'id',
                            title: __('Id')
                        },
                        {
                            field: 'type',
                            title: __('Type'),
                            searchList: {
                                "skip": __('Type skip'),
                                "mark": __('Type mark')
                            },
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'name',
                            title: __('Category_id')
                        },
                        {
                            field: 'title',
                            title: __('Title')
                        },
                        ]
                    ]
                });

                // 为表格1绑定事件
                Table.api.bindevent(table);


                let that = this;
                // 获取选中项
                $(document).on("click", ".btn-selected", function () {
                    let question = table.bootstrapTable('getSelections');
                    question.sort((a, b) => {
                        return a.id - b.id;
                    })
                    let is_ = false;
                    question.forEach((item, index) => {
                        if (that.data.indexOf(item.id) == -1) {
                            that.data.push(item.id);
                            that.refresh(item, that.data.length - 1);
                        } else {
                            is_ = true;
                        }
                    })
                    if (is_) {
                        Toastr.error(Fast.lang('Repeat problem filtered!'));
                    }
                });
            },
            refresh: function (item, index) {
                let st = Fast.lang('Jump topic');
                let sr = Fast.lang('Jump results');
                let html = `
                      <div class="json_list">
                            <div class="json_left">
                                <div class="question">
                                    <input type="text" class="form-control" value="${item.id}、${item.title}" readonly/>
                                    <input type="hidden" name="row[${index}][id]" value="${item.id}"/>
                                    </div>
                                    `;
                let question = item.question_text;
                question.forEach((it, id) => {
                    html += `
                                        <div class="answer">
                                        <input type="text" class="form-control"
                                        value="${it.option}：${it.intro}" readonly/>
                                        <input type="hidden" name="row[${index}][option][${id}]" value="${it.option}"/>
                                       <input type="text" name="row[${index}][skip][${id}]" class="form-control"
                                           value="0" style="margin: 0 3px;" placeholder="${st}"/>
                                       <input type="text" name="row[${index}][result][${id}]" class="form-control"
                                           value="0" placeholder="${sr}"/>
                                   </div> 
                               `;
                })

                html += `
                            </div>
                            <div>                               
                                <span class="btn btn-sm btn-danger btn-remove" data-question="${item.id}">
                                    <i class="fa fa-times"></i>
                                </span>
                                <span class="btn btn-sm btn-primary btn-dragsort">
                                    <i class="fa fa-arrows"></i>
                                </span>
                            </div>
                        </div>
                    `;
                $("#question").append(html);
            }
        },
        component: function () {

            Controller.api.bindevent();

            var vm = new Vue({
                el: '#app',
                data() {
                    return {
                        component_ids: [],
                        list: [],
                        question: [],
                        result: []
                    }
                },
                created() {
                    this.list = JSON.parse(lists);
                    //赋值
                    this.component_ids = this.list.map(item => item.id + '');
                },
                methods: {
                    search(e) {
                        console.log(e)
                    },
                    selectQuestion(index) {
                        let that = this;
                        Fast.api.open('mental/question/select', '选择问题', {
                            callback: function (value) {
                                //判断是否存在
                                let qid = that.list[index].question.map(item => item.id + '');
                                value.forEach(item => {
                                    if (!qid.includes(item.id + '')) {
                                        that.list[index].question.push(item);
                                    }
                                })
                            }
                        })
                    },
                    remove(index, ik) {
                        this.list[index].question.splice(ik, 1);
                    },
                    //追加结果
                    addResult(index) {
                        this.list[index].result.push({
                            title: '',
                            left: '',
                            right: '',
                            content: ''
                        })
                    },
                    removeResult(index, key) {
                        this.list[index].result.splice(key, 1)
                    }
                }
            })
            //下拉选择驱动
            $("#c-component_id").data("params", function (obj) {
                let component_texts = $("#c-component_id").selectPageText();
                let component_ids = $("#c-component_id").val();
                if (!component_ids) {
                    vm.component_ids = [];
                    vm.list = [];
                    vm.question = [];
                    return;
                }
                //每次都是全部
                let component_ids_arr = component_ids.split(',');
                let component_text_arr = component_texts.split(',');
                //先移除
                vm.component_ids.forEach((id, index) => {
                    if (!component_ids_arr.includes(id)) {
                        vm.list.splice(index, 1);
                        vm.component_ids.splice(index, 1);
                    }
                })
                //不存在就追加，按顺序的                
                component_ids_arr.forEach((id, index) => {
                    if (!vm.component_ids.includes(id)) {
                        vm.component_ids.push(id);
                        vm.list.push({
                            id: id,
                            title: component_text_arr[index],
                            type: 1,
                            question: [],
                            result: []
                        });
                    }
                })
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        edit_dimension: function () {
            Controller.api.bindevent();
        },
        ruleconfig: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});